package com.mycompany.application;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;

import java.io.InputStream;

import android.view.WindowManager.LayoutParams;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
    private static final int REQUEST_CODE_DRAW_OVERLAY = 1234;

    private boolean status = false;

    private Point point;

    private WindowManager manager;

    private WindowManager.LayoutParams vParams;

    private View vTouch;

    // 绘制窗口
    private WindowManager DrawManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 透明状态栏和导航栏
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 透明状态栏
        this.getWindow().addFlags(LayoutParams.FLAG_TRANSLUCENT_STATUS);
        this.getWindow().addFlags(LayoutParams.FLAG_LAYOUT_IN_SCREEN);
        this.getWindow().addFlags(LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        // 透明导航栏
        this.getWindow().addFlags(LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        this.getWindow().addFlags(LayoutParams.FLAG_TRANSLUCENT_STATUS);

        // 渲染视图
        setContentView(R.layout.activity_main);

        // 申请悬浮权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                    Uri.parse("package:" + getPackageName()));
            startActivityForResult(intent, REQUEST_CODE_DRAW_OVERLAY);
        }

        // 装载字体文件
        try {
            InputStream in = getAssets().open("zt.ttf");
            GLES3JNIView.fontData = new byte[in.available()];
            in.read(GLES3JNIView.fontData);
        } catch (Exception e) {
            Log.e("MainActivity", "Error loading font data: " + e.getMessage());
        }
    }

    public void onClick(View v) {
        // 校验密码是否正确
        EditText editText = findViewById(R.id.editTextUsername);
        String userInput = editText.getText().toString();

        // 可以使用服务端校验
        if (!userInput.equals("skong")) {
            Toast.makeText(this, "密码错误", Toast.LENGTH_SHORT).show();
        } else {
            if (!this.status) {
                this.start();
                // 移除不要的视图
                this.removeView(R.id.loginButton);
                this.removeView(R.id.editTextUsername);
            }
        }
    }

    private void removeView(int id) {
        try {
            View v = findViewById(id);
            // 找到父布局
            ViewGroup parentLayout = (ViewGroup) v.getParent();
            // 移除视图
            parentLayout.removeView(v);
        } catch (RuntimeException e) {
            Log.e("error", e.toString());
        }
    }

    private void start() {
        // 标志状态
        this.status = true;

        DrawManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);

        // 双悬浮方案，解决触摸问题
        manager = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        vParams = getAttributes(false);

        WindowManager.LayoutParams wParams = getAttributes(true);
        GLES3JNIView display = new GLES3JNIView(this);

        vTouch = new View(this);
        manager.addView(vTouch, vParams);
        manager.addView(display, wParams);

        // 获取悬浮窗触摸
        vTouch.setOnTouchListener(new View.OnTouchListener() {
            @SuppressLint("ClickableViewAccessibility")
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                switch (action) {
                    case MotionEvent.ACTION_MOVE:
                    case MotionEvent.ACTION_DOWN:
                    case MotionEvent.ACTION_UP:
                        GLES3JNIView.MotionEventClick(action != MotionEvent.ACTION_UP, event.getRawX(),
                                event.getRawY());
                        break;
                    default:
                        break;
                }
                return false;
            }
        });
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    String[] rect = GLES3JNIView.getWindowRect().split("\\|");
                    vParams.x = Integer.parseInt(rect[0]);
                    vParams.y = Integer.parseInt(rect[1]);
                    vParams.width = Integer.parseInt(rect[2]);
                    vParams.height = Integer.parseInt(rect[3]);
                    manager.updateViewLayout(vTouch, vParams);
                } catch (Exception ignored) {
                }
                handler.postDelayed(this, 20);
            }
        }, 20);

        point = new Point();
        // 获取真实分辨率(翻转屏幕的时候自动获取)(不支持安卓12，自己适配)
        vTouch.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                DrawManager.getDefaultDisplay().getRealSize(point);
                GLES3JNIView.real(point.x, point.y);
            }
        });
    }

    @SuppressLint("RtlHardcoded")
    private WindowManager.LayoutParams getAttributes(boolean isWindow) {
        WindowManager.LayoutParams params = new WindowManager.LayoutParams();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            params.type = WindowManager.LayoutParams.TYPE_PHONE;
        }
        params.flags = WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION
                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;

        if (isWindow) {
            params.flags |= WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                    | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
        }
        params.format = PixelFormat.RGBA_8888; // 设置图片格式，效果为背景透明
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            params.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
        }
        params.gravity = Gravity.LEFT | Gravity.TOP; // 调整悬浮窗显示的停靠位置为左侧置顶
        params.x = 0;
        params.y = 0;
        params.width = params.height = isWindow ? WindowManager.LayoutParams.MATCH_PARENT : 0;
        return params;
    }
}
